﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace BlogDemo.Api.Infrastructure.Extensions
{
    public static class EnumerableExt
    {
        public static IEnumerable<ExpandoObject> ToDynamic<T>(this IEnumerable<T> source, string fields = null)
            where T : class, new()
        {
            if (source == null)
            {
                throw new ArgumentNullException("Source is not allowed null");
            }
            var props = new List<PropertyInfo>();
            var objs = new List<ExpandoObject>();
            if (string.IsNullOrEmpty(fields))
            {
                props.AddRange(typeof(T).GetProperties());
            }
            else
            {
                var filedArr = fields.Split(",");
                foreach (var field in filedArr)
                {
                    var prop = typeof(T).GetProperty(field);
                    if (prop != null)
                    {
                        props.Add(prop);
                    }
                }
            }

            foreach (var item in source)
            {
                var obj = new ExpandoObject();
                foreach (var prop in props)
                {
                    var val = prop.GetValue(item);
                    obj.TryAdd(prop.Name,val);
                }
                objs.Add(obj);
            }
            return objs;
        }
    }
}
